package cn.codewen.dao.impl;

import cn.codewen.dao.UserDao;
import cn.codewen.pojo.User;
import cn.codewen.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class UserDaoImpl implements UserDao {

    //0. 定义conn和stm
    private Connection conn;
    private Statement stm;

    //1. 构造方法
    public UserDaoImpl() {
        try {
            //1.1. 得到连接
            conn = JDBCUtils.getConnection();
            //1.2. 创建stm对象
            stm = conn.createStatement();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public User getOneByUsername(String username) {
        //0. 声明一个User对象
        User user = null;
        try {
            //1. 定义SQL语句
            String sql = "select * from user where username='" + username + "'";
            //2. 执行SQL语句
            ResultSet rs = stm.executeQuery(sql);
            //3. 遍历rs
            if (rs.next()) {
                user = new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
            }
            //4. 关闭对象
            //JDBCUtils.close(rs, stm, conn);
            rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //5. 返回数据
        return user;
    }

    @Override
    public User insert(User user) {
        //0. 声明一个User对象
        try {
            //1. 定义SQL语句
            String sql = "insert into user (username, password, sex) VALUES ('" + user.getUsername() + "','" + user.getPassword() + "'," + user.getSex() + ")";
            //2. 执行SQL语句
            int i = stm.executeUpdate(sql);
            //3. 遍历rs
            if (i > 0) {
                return user;
            } else {
                return null;
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return null;

    }
}
